from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from seller import models

# Create your views here.
# MD5加密
'''
1.单向加密  （不可逆）  
2.固定内容加密后生成相同的密文
3.密文长度相同
'''
import hashlib


#  MD5加密方式
def pwd_md5(password):
    m = hashlib.md5()
    m.update(password.encode('utf-8'))
    ret = m.hexdigest()
    return ret
    # return hashlib.md5(password.encode('utf-8')).hexdigest


# 注册
def register(request):
    if request.method == 'POST':
        # 1.获取表单提交的内容
        name = request.POST.get('username')
        pwd = request.POST.get('password')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        gender = request.POST.get('gender')
        headimg = request.FILES.get('headimg')
        # 2. 保存数据库 保存头像
        seller = models.Seller()
        seller.name = name
        seller.pwd = pwd_md5(pwd)
        seller.email = email
        seller.phone = phone
        seller.address = address
        seller.gender = gender
        seller.image = headimg
        seller.save()
        # 3. 响应 重定向到登录
        return redirect('/seller/login/')
    return render(request, 'seller/register.html')


# 注册判断是否用户已存在
def register_ajax(request):
    name = request.GET.get('username')
    name1 = models.Seller.objects.filter(name=name).first()
    if name1:
        dic = {'msg': '用户名已经存在', 'code': 200}
    else:
        dic = {'msg': '', 'code': 100}
    return JsonResponse(dic)


# 管理员登录
def login(request):
    msg = ''
    if request.method == 'POST':
        name = request.POST.get('username')
        pwd = request.POST.get('password')
        pwd = pwd_md5(pwd)
        print(name, pwd)
        seller = models.Seller.objects.filter(name=name, pwd=pwd).first()
        if seller:
            response = redirect('/seller/index/')
            response.set_cookie('name', name)
            image = seller.image
            response.set_cookie('headimg', image)
            response.set_cookie('id', seller.id)
            return response
        else:
            msg = '用户名或密码错误'
    return render(request, 'seller/login.html', {'msg': msg})


# 首页
def index(request):
    return render(request, 'seller/index.html')


# 管理员登出
def logout(request):
    response = redirect('/seller/login/')
    response.delete_cookie('name')
    response.delete_cookie('headimg')
    response.delete_cookie('id')
    return response


# 给首页返回数据
def index_ajax(request):
    # 返回当前用户的商品和类型
    seller_id = request.COOKIES.get('id')
    store = models.Store.objects.get(seller_id=seller_id)
    # 川所有收纳功能类型
    goods_type_list = models.GoodsType.objects.all()
    print(goods_type_list)
    new_list = []
    for goods_type in goods_type_list:
        goodslist = goods_type.goods_set.filter(store_id=store.id)
        goods_number = len(goodslist)
        dic = {}
        dic['typeName'] = goods_type.name
        dic['number'] = goods_number
        new_list.append(dic)
    print(new_list)
    # goods_list = models.Goods.objects.filter(store_id=store.id)
    # for goods in goods_list:
    #     print(goods.name)
    #     types = models.Goods.objects.filter(name=goods.name)
    #     print(types[0].goodsType.name)

    return JsonResponse({'data': new_list})


# 店铺展示判断他的专递方式  修改# 判断他的logo是否获取到数据    增加
def store(request):
    ################ 获取到当前登录的id
    id = request.COOKIES.get('id')
    print(id)
    if request.method == 'POST':
        name = request.POST.get('shopname')
        address = request.POST.get('shopaddress')
        desc = request.POST.get('shopdesc')
        logo = request.FILES.get('shopimg')
        print(name, address, desc, logo)
        store = models.Store.objects.filter(seller_id=id).first()
        # 判断是添加还是修改
        # 修改店铺
        if store:
            store.name = name
            store.address = address
            store.desc = desc
            older_logo = store.logo  # 对象
            # print(older_logo)
            # 获取到logo 看logo是否是空的（value值是否获取到） 如果是空的就不删除 如果不为空就把之前的删掉再添加新的logo
            if logo:
                older_logo.delete()  # ##############  看返回对象的底层是否有这个方法
                store.logo = logo
            store.save()
            return redirect('/seller/store/')
        else:
            # 通过cookie里面的用户id 判断该用户是否有店铺 如果没有则，增加店铺
            store = models.Store()
            store.name = name
            store.address = address
            store.desc = desc
            store.logo = logo
            # 从cookie中找对象
            store.seller_id = id
            store.save()
            return redirect('/seller/index/')
    else:
        # 展示
        store = models.Store.objects.filter(seller_id=id).first()
        print(store)
        return render(request, 'seller/store.html', {'store': store})


# 商品类型列表
def goods_type_list(request):
    goods_type_list = models.GoodsType.objects.all()
    return render(request, 'seller/goods_type_list.html', locals())


#  添加商品类型
def add_goods_type(request):
    # 获取表单
    name = request.POST.get('goodstype_name')
    logo = request.FILES.get('goodstype_img')
    # 保存数据库
    goods_type = models.GoodsType()
    goods_type.name = name
    goods_type.logo = logo
    goods_type.save()
    # 响应 重定向到商品
    return redirect('/seller/goods_type_list')


#  修改商品类型
def goods_type_update(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        name = request.POST.get('goodstypename')
        image = request.FILES.get('goodstypeimg')
        goods_type = models.GoodsType.objects.get(id=id)
        logo = goods_type.logo
        print(logo, image)
        goods_type.name = name
        # 如果在前面的value中获取到值，就把之前的删掉  此照片的删除同下面的删除方式一样
        if image:
            logo.delete()
            goods_type.logo = image
        goods_type.save()
        return redirect('/seller/goods_type_list/')
    else:
        id = request.GET.get('id')
        goods_type = models.GoodsType.objects.get(id=id)
        logo = goods_type.logo
        print(type(logo))
        return render(request, 'seller/edit_goodstype.html', locals())


#  删除商品类型
def goods_type_delete(request):
    id = request.GET.get('id')
    goods_type = models.GoodsType.objects.get(id=id)
    goods_type.logo.delete()
    # 删除的时候不能把之前的照片删除，需要把原始的照片删除掉。 获取到之前的照片是一个对象，直接调用对象的删除方法删除即可！
    models.GoodsType.objects.get(id=id).delete()
    return redirect('/seller/goods_type_list/')


#  获取商品
def goods_list(request):
    # 拿我手里的id  根据id 查找店铺的名字  根据店铺和商品的关联 来确定 id的唯一性
    id = request.COOKIES.get('id')
    print(id)
    store = models.Store.objects.filter(seller_id=id).first()
    goodslist = models.Goods.objects.filter(store_id=store.id)
    return render(request, 'seller/goods_list.html', locals())


#  添加商品
def add_goods(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        bzq = request.POST.get('bzq')
        productdate = request.POST.get('productdate')
        desc = request.POST.get('desc')
        content = request.POST.get('content')
        goodsimg = request.FILES.get('goodsimg')
        goods_type_id = request.POST.get('goodstype_id')
        goods = models.Goods()
        goods.name = name
        goods.price = price
        goods.bzq = bzq
        goods.prodate = productdate
        goods.desc = desc
        goods.details = content
        goods.goodsimg = goodsimg
        goods.goodsType_id = goods_type_id
        # 查询店铺
        seller_id = request.COOKIES.get('id')
        store = models.Store.objects.get(seller_id=seller_id)
        goods.store = store
        goods.save()
        return redirect('/seller/goods_list/')
    else:
        # 获取商品类型
        goods_type = models.GoodsType.objects.all()
        # 展示
        return render(request, 'seller/add_goods.html', locals())
